package com.dp.mallchat.common.common.event.listener;

import com.dp.mallchat.common.common.event.UserRegisterEvent;
import com.dp.mallchat.common.user.domain.user.entity.User;
import com.dp.mallchat.common.user.domain.user.enums.IdempotenceEnum;
import com.dp.mallchat.common.user.service.UserBackpackService;
import com.dp.mallchat.common.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import static com.dp.mallchat.common.user.domain.user.enums.ItemEnum.*;

/**
 * @Author: dupeng
 * @CreateTime: 2024-06-09  15:04
 * @Description: 用户注册监听器
 */
@Component
public class UserRegisterEventListener {

    public static final int TOP_10 = 10;
    public static final int TOP_100 = 100;
    @Autowired
    private UserBackpackService userBackpackService;
    @Autowired
    private UserService userService;

    @Async
    @EventListener(classes = UserRegisterEvent.class)
    public void sendCard(UserRegisterEvent event) {
        User user = event.getUser();
        userBackpackService.acquireItem(user.getId(), MODIFY_NAME_CARD.getId(), IdempotenceEnum.UID, user.getId().toString());
    }

    @Async
    @EventListener(classes = UserRegisterEvent.class)
    public void sendBadge(UserRegisterEvent event) {
        User user = event.getUser();
        int count = userService.count();    // 存在并发问题和性能瓶颈，用户多了这部分将删除
        // 获取前10,100名用户发放徽章
        if (count <= TOP_10) {
            userBackpackService.acquireItem(user.getId(), REG_TOP10_BADGE.getId(), IdempotenceEnum.UID, user.getId().toString());
        } else if (count <= TOP_100) {
            userBackpackService.acquireItem(user.getId(), REG_TOP100_BADGE.getId(), IdempotenceEnum.UID, user.getId().toString());
        }
    }


}
